package com.mk.auth.api;

import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.model.response.Rsp;
import com.mk.model.entity.Resource;
import com.mk.model.entity.Role;
import com.mk.model.entity.User;
import com.mk.model.request.LoginRequest;
import com.mk.model.response.LoginResponse;
import com.mk.service.IAuthService;
import com.mk.service.IResourceService;
import com.mk.service.IRoleService;
import com.mk.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 4:42 PM 3/13/18
 */
@RestController
@RequestMapping("/auth")
public class AuthApi {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private IAuthService authService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IResourceService resourceService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Rsp<LoginResponse> createAuthenticationToken(@RequestBody LoginRequest request){
        try {
            if (request == null)
                throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(), "请传入登录信息");
            String username = request.getUsername();
            String password = request.getPassword();
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
                throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(), "登录时用户名或者密码不可为空");
            final String token = "Bearer " + authService.login(username, password);
            List<Role> roles = roleService.getByUsername(username);
            List<Resource> reses = resourceService.getByUsername(username);
            Set<String> pers = resourceService.getCodesByUsername(username);
            User user = userService.get(username);
            return Rsp.SUCCESS(new LoginResponse(user.getId(),token,user,roles,reses,pers));
        }catch (Exception e){
            if(e instanceof ApplicationException)
                return Rsp.ERROR(e.getMessage());
            else
                return Rsp.ERROR("用户名或密码有误！");
        }
    }



    @RequestMapping(value = "/refresh", method = RequestMethod.GET)
    public Rsp<String> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws org.springframework.security.core.AuthenticationException {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if(refreshedToken == null) {
            throw new ApplicationException(StatusCode.UNAUTHORIZED.getCode(),"请重新登陆!");
        } else {
            return Rsp.SUCCESS("Bearer "+refreshedToken);
        }
    }

//    @RequestMapping(value = "/register", method = RequestMethod.POST)
//    public User register(@RequestBody User addedUser) throws AuthenticationException{
//        return authService.register(addedUser);
//    }
}
